#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include "pthreadPool.hpp"
#define NUMSIZE 1024
const int listen_queue_flag = 20;
void func(pthreadPool<std::string> &pt, int sock)
{
    char buffer[NUMSIZE];
    memset(buffer, 0, NUMSIZE);
    ssize_t s = recv(sock, buffer, NUMSIZE, 0);
    std::cout << buffer << std::endl;
    if (s > 0)
    {
        std::string bufe = buffer;
        pt.run(bufe, sock);
    }
}
// 主函数
int main(int argc, char *argv[])
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    if (argc != 2)
    {
        std::cout << "格式错误" << std::endl;
        exit(1);
    }
    // 创建套接字
    int listensock = socket(AF_INET, SOCK_STREAM, 0);
    if (listensock < 0)
    {
        std::cout << "socket enrro" << std::endl;
        exit(1);
    }
    // 开始绑定
    sockaddr_in local;
    local.sin_addr.s_addr = inet_addr("0.0.0.0");
    local.sin_family = AF_INET;
    local.sin_port = htons(atoi(argv[1]));
    int ret = bind(listensock, (sockaddr *)&local, sizeof(local));
    if (ret < 0)
    {
        std::cout << "bind enrro" << std::endl;
        exit(2);
    }
    // 监听
    int listens = listen(listensock, listen_queue_flag);
    if (listens < 0)
    {
        std::cout << "listen enrro" << std::endl;
        exit(3);
    }
    // 建立线程池
    pthreadPool<std::string> *pstr = pthreadPool<std::string>::get();
    pstr->start();
    // 建立链接
    while (true)
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int sersock = accept(listensock, (sockaddr *)&client, &len);
        if (sersock < 0)
        {
            std::cout << "accept enrro" << std::endl;
            continue;
        }
        func(*pstr, sersock);
    }
    return 0;
}